
var strPage = null, strMode = null;
var oXML = null, oXSL = null;
var strRepoPath = "repository/", strRepo = "default";

$(document).ready( function() { 

	strPage = getParameter( "page" );
	if ( strPage == null || strPage == "" )
		strPage = "home";

	if ( strMode == null || strMode == "" )
		strMode = "view";

	populateMenu();
	reload();

	function reload() {
		try {
			var strXML = strRepoPath + strRepo + "/" + strPage + ".xml";
			var strXSL = "xsl/"  + strMode + ".xsl";
			message( "Doing reload() with: " + strXML + " and " + strXSL );
			if ( oXML == null ) {
				$.ajax( { url: strXML, type: 'GET', timeout: 1000, cache: false, async: false,
					error: reportAjaxError,	complete: function( oXMLHttpRequest ) {
						oXML = parseStringToXML( oXMLHttpRequest.responseText ); }
				} );
				var strTitle = $( oXML ).contents().attr( "title" );
				$( "#wixi_page_title" ).empty().append( strTitle );
				document.title = strTitle;
				$( "#wixi_show_xml_doc" ).empty().append( strXML );
			}
			$.ajax( { url: strXSL, type: 'GET', timeout: 1000, cache: false, async: false,
				error: reportAjaxError, success: function( oDoc ) { oXSL = oDoc; }
			} );
			if ( oXML != null && oXSL != null ) {
				$( "#wixi_page_main" ).empty();
				transformObjs( oXML, oXSL, "wixi_page_main" );
				$( "textarea" ).each( function() {
					$(this).text( $(this).next().html() );
					$(this).next().empty();
				} );
				$( "#wixi_show_xsl_doc" ).empty().append( strXSL );
//				$( "#wixi_button_save" ).click( function() { processForm(); } );
				$('#wixi_form').ajaxForm( { beforeSubmit: processRequest } ); 
				$('.WIXI_FCK_TEXTAREA').fck( { path: 'style/fckeditor/' } );
			}
//			window.top.location.search = "?page=" + strPage + "&mode=" + strMode;
		} catch ( e ) {
			message( e.toString() );
		}
	}

	function processRequest( formData, jqForm, options ) {
		if ( strMode == "edit" ) {
			for ( iX = 0; iX < formData.length; iX++ ) {
				var strName  = formData[iX].name;
				var strValue = formData[iX].value;
				if ( strName == "wixi_button_save" )
					continue;
// Shame this doesn't work
				$( oXML ).contents().find( "#" + strName + "[@type='richtext']" ).each( function() {
					$(this).empty();
					$(this).append( jQuery( strValue ) );
//					$(this).append( strValue );
//					var oNewPieces = jQuery( strValue );
//					for ( i = 0; i < oNewPieces.length; i++ )
//						this.appendChild( oNewPiece[i] );
				} );
//				$( oXML ).contents().find( "#" + strName + "[@type='richtext']" ).get().appendChild( parseStringToXML( strValue ) );
				$( oXML ).contents().find( "#" + strName + "[type!='richtext']" ).text( strValue );
			}
		} else if ( strMode == "copy" ) {
			for ( iX = 0; iX < formData.length; iX++ ) {
				var strName  = formData[iX].name;
				var strValue = formData[iX].value;
				if ( strName == "wixi_button_save" )
					continue;
				if ( strName == "wixi_copy_page_name" )
					strPage = strValue;
				$( oXML ).contents().find( "#" + strName ).text( strValue );
			}
		} else if ( strMode == "rawedit" ) {
			for ( iX = 0; iX < formData.length; iX++ ) {
				var strName  = formData[iX].name;
				var strValue = formData[iX].value;
				if ( formData[iX].name == "wixi_rawedit_text" ) {
					oXML = parseStringToXML( strValue );
				}
			}
		}
		message( 'About to submit: \n\n' + $.param( formData ) );
		savePage();
		if ( strMode == "copy" )
			reload();
		return false;		// prevent standard submit
	}

	function transformObjs( oXML, oXSL, strHTMLElmtId ) {
		// code for IE
		if ( window.ActiveXObject ) {
			ex=oXML.transformNode( oXSL );
			document.getElementById( strHTMLElmtId ).innerHTML=ex;
		// code for Mozilla, Firefox, Opera, etc.
		} else if ( document.implementation && document.implementation.createDocument ) {
			xsltProcessor = new XSLTProcessor();
			xsltProcessor.importStylesheet( oXSL );
			resultDocument = xsltProcessor.transformToFragment( oXML, document );
			document.getElementById( strHTMLElmtId ).appendChild( resultDocument );
		}
	}

	function savePage() {
//		$.ajax( { url: "store", type: "POST", processData: false, data: oXML,
		var strXML = strRepoPath + strRepo + "/" + strPage + ".xml";
		$.ajax( { url: strXML, type: "POST", processData: false, data: oXML,
			username: "", password: "",
//			beforeSend: function( oXMLHttpRequest ) {
//				oXMLHttpRequest.setRequestHeader( "topic_id", strPage ); },
			success: function() {
				message( "Saved to disk" ); },
			error: function( oXMLHttpRequest, strText, errorThrown ) {
				message( "Disk save failed: " + strText ); }
		} );
	}

	function info() {
		var strXML = strRepoPath + strRepo + "/" + strPage + ".xml";
		var strXSL = "xsl/pageinfo.xsl";
		message( "Doing info() with: " + strXML );
//		var strRqst = '<?xml version="1.0" encoding="utf-8" ?><D:version-tree xmlns:D="DAV:">'
//			+ '<D:prop><D:version-name/><D:creator-displayname/><D:successor-set/></D:prop></D:version-tree>';
		var strRqst = '<?xml version="1.0" encoding="utf-8" ?><D:propfind xmlns:D="DAV:"><D:allprop/></D:propfind>';
		var strResp = "[n/a]";
		var oResp = null;
		$.ajax( { url: strXML, type: 'PROPFIND', timeout: 1000, cache: false, async: false, processData: false, data: strRqst,
			error: reportAjaxError,	complete: function( oXMLHttpRequest ) {
				oResp = parseStringToXML( oXMLHttpRequest.responseText ); }
		} );
		$.ajax( { url: strXSL, type: 'GET', timeout: 1000, cache: false, async: false,
			error: reportAjaxError, success: function( oDoc ) { oXSL = oDoc; }
		} );
//		$( "#wixi_page_main" ).empty().append( "div" ).text( strResp );
		$( "#wixi_page_main" ).empty();
		transformObjs( oResp, oXSL, "wixi_page_main" );
	}

	function changeMode( strNewMode ) {
		if ( strNewMode != strMode ) {
			strMode = strNewMode;
			if ( strMode == 'info' )
				info();
			else
				reload();
		}
	}

	function populateMenu() {
		$( "#wixi_link_view"    ).click( function() { changeMode( 'view'    ); } );
		$( "#wixi_link_copy"    ).click( function() { changeMode( 'copy'    ); } );
		$( "#wixi_link_edit"    ).click( function() { changeMode( 'edit'    ); } );
		$( "#wixi_link_rawedit" ).click( function() { changeMode( 'rawedit' ); } );
		$( "#wixi_link_xml"     ).attr( "href", strRepoPath + strRepo + "/" + strPage + ".xml" );
		$( "#wixi_link_info"    ).click( function() { changeMode( 'info' ); } );
	}

	function reportAjaxError( oXMLHttpRequest, strTextStatus, oErrorThrown ) {
		var strMessage = this.url + ", " + strTextStatus;
		if ( oErrorThrown != null )
			strMessage += ", " + oErrorThrown.toString();
		message( strMessage );
	}

	function message( strMsg ) {
		$( "#wixi_message_bar" ).empty().append( strMsg );
	}

	function parseStringToXML( strText ) {
		if ( window.ActiveXObject ) {
			var oXMLDoc = new ActiveXObject('Microsoft.XMLDOM');
			oXMLDoc.async = false;
			if ( oXMLDoc.loadXML( strText ) ) {
				return oXMLDoc;
			} else {
				message( oXMLDoc.parseError.reason + "\t" + oXMLDoc.parseError.srcText );
			}
			// code for Mozilla, Firefox, Opera, etc.
		} else if ( document.implementation && document.implementation.createDocument ) {
			var domParser   = new DOMParser();
			var oXMLDoc     = domParser.parseFromString( strText, 'application/xml' );
			var oParseError = checkForParseError( oXMLDoc );
			if ( oParseError.errorCode == 0 ) {
				return oXMLDoc;
			} else {
				message( oParseError.reason + "\t" + oParseError.srcText );
			}
		}
	}

	function checkForParseError( oXMLDoc ) {
		var strErrorNS  = 'http://www.mozilla.org/newlayout/xml/parsererror.xml';
		var oDocElmt    = oXMLDoc.documentElement;
		var oParseError = { errorCode : 0 };
		if ( oDocElmt.nodeName == 'parsererror' && oDocElmt.namespaceURI == strErrorNS ) {
			oParseError.errorCode = 1;
			var oSourceText = oDocElmt.getElementsByTagNameNS( strErrorNS, 'sourcetext' )[0];
			if ( oSourceText != null ) {
				oParseError.srcText = oSourceText.firstChild.data;
			}
			oParseError.reason = oDocElmt.firstChild.data;
		}
		return oParseError;
	}

	function getParameter( strParameterName ) {
		var strQueryString = window.top.location.search.substring(1);
		var strParameterName = strParameterName + "=";		// Add "=" to the parameter name (i.e. parameterName=value)
		if ( strQueryString.length > 0 ) {
			var iBegin = strQueryString.indexOf ( strParameterName );				// Find the beginning of the string
			if ( iBegin != -1 ) {							// If the parameter name is not found, skip it, otherwise return the value
				iBegin += strParameterName.length;									// Add the length (integer) to the beginning
				var iEnd = strQueryString.indexOf( "&", iBegin );					// Multiple parameters are separated by the "&" sign
				if ( iEnd == -1 ) {
					iEnd = strQueryString.length
				}
				return unescape( strQueryString.substring ( iBegin, iEnd ) );		// Return the string
			}
			return null;															// Return null if no parameter has been found
		}
	}

} );

/*

NOT CURRENTLY USED...

//	if ( strMode == "rawedit" )
//		rawedit();
//	else

	function processForm() {
		if ( strMode == "copy" ) {
			var strNewTopicId = $( "#NEW_TOPIC" ).val();
			if ( strNewTopicId == "" ) {
				message( "Please specify a new topic id" );
				return;
			}
			strPage = strNewTopicId;
		}
		$.fck.update();
		$( "input" ).each( function() {
			var strName = $(this).attr( "name" );
			var strText = $(this).val();
			var oInputNode = $( oXML ).find( "field[id=" + strName + "]" ).get()[0];
			if ( oInputNode && oInputNode.childNodes ) {
				for ( iX = 0; iX < oInputNode.childNodes.length; iX++ ) {
					if ( oInputNode.childNodes[iX].nodeType == 3 )			// Text node
						oInputNode.childNodes[iX].nodeValue = strText;
				}
			}
		} );
		$( "textarea" ).each( function() {
			var strName = $(this).attr( "name" );
			var strText = $(this).val();
			var oNewXML = parseStringToXML( strText );
			var oTextareaNode = $( oXML ).find( "field[id=" + strName + "]" ).get()[0];
			if ( oTextareaNode && oTextareaNode.childNodes ) {
				for ( iX = 0; iX < oTextareaNode.childNodes.length; iX++ ) {
					if ( oTextareaNode.childNodes[iX].nodeType != 2 )			// Attribute node
						oTextareaNode.removeChild( oTextareaNode.childNodes[iX] );
				}
			}
			if ( oNewXML != null )
				oTextareaNode.appendChild( oNewXML );
		} );
		message( 'Saved in memory' );

		if ( strMode == "copy" ) {
			strMode = "edit";
			reload();
		}
	}

*/